Compañías: Google, Facebook, Microsoft, Twitter, AirBnB, IBM, Uber, AWS, HP, Novartis, Ford, etc.
Periodismo: BBC, Buzzfeed, The Economist, Financial Time, New York Times, etc.
Gobiernos: El Gobierno del Reino Unido, el estado de Indiana, Ciudad de Chicago, etc.
Bancos/Finanzas: HSBC, J.P. Morgan, Morgan Stanley, Citibank, Fidelity, Bank of America, AMEX, etc.
Otros: Gartner, AC Nielsen, Deloitte Consulting, Accenture, PricewaterhouseCoopers, Target, etc.
El ciclo de análisis: importar datos, limpiarlos, transformarlos, visualizarlos, modelarlos, y al final, comunicar los hallazgos

Referencia: “R for Data Science”, G. Grolemund y H. Wickham
# ref: https://stackoverflow.com/questions/19343133/setting-upper-and-lower-limits-in-rnorm
set.seed(2019)
gen_notas <- function(n, avg, sd, min, max, nmuestra) {
muest <- rnorm(nmuestra, avg, sd)
muest <- muest[muest >= min & muest <= max]
if (length(muest) >= n) {
return(sample(muest, n))
} else {
stop(simpleError("No hay datos suficientes. Aumenta 'nmuestra'"))
}
}
notas <- round(gen_notas(100, 13, 4, 4, 17, 1000), 1)
head(notas, 15)## [1] 4.4 14.8 14.0 7.3 8.0 13.8 8.8 14.2 8.7 9.0 8.6 16.8 9.0 13.0
## [15] 10.2
## [1] 11.636
## [1] 4.4 16.8
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 4.400 9.475 11.550 11.636 14.000 16.800
hist(notas, breaks = 15, main = "Distribución de notas")
abline(v = mean(notas), col = "blue", lwd = 3)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 4.400 9.475 11.550 11.636 14.000 16.800
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 6.40 11.47 13.55 13.64 16.00 18.80
d <- data.frame(antes = notas, despues = notas2)
ggplot(d) +
geom_density(aes(x = antes), fill = "red", alpha = 0.8) +
geom_density(aes(x = despues), fill = "blue", alpha = 0.8) +
xlim(0, 20)
iris) que contiene lirios de tres especies, y datos de longitud y ancho de los pétalos y sépalos.

ggplot(iris, aes(x = Sepal.Length, y = Petal.Width, color = Species)) +
geom_mark_hull(aes(label = Species), show.legend = FALSE) + # agrupar
geom_point(show.legend = FALSE) +
theme_light() + # un tema mas simple
labs( # etiquetas del gráfico
title = "Los tres tipos de lirios",
x = "Longitud de los sépalos (cm)",
y = "Ancho de los pétalos (cm)"
) +
theme( # cambiar la fuente del título
plot.title = element_text(family = "Elegante", size = 24)
)x
La composición de los partidos/bancadas en el Congreso de la República ha variado desde el 2016 a la fecha.
Intentaremos mostrar este cambio en forma gráfica, usando la información existente en Wikipedia.
library(tidyverse)
library(rvest)
original_xpath <- "/html/body/div[3]/div[3]/div[4]/div/table[3]"
actual_xpath <- "/html/body/div[3]/div[3]/div[4]/div/table[4]"
wiki_url <- "https://es.wikipedia.org/wiki/Periodo_parlamentario_2016-2021_del_Congreso_de_la_Rep%C3%BAblica_del_Per%C3%BA"
c2016 <- read_html(wiki_url)
original_node <- html_node(c2016, xpath = original_xpath)
actual_node <- html_node(c2016, xpath = actual_xpath)
original_df <- html_table(original_node)
actual_df <- html_table(actual_node, fill = TRUE)# composición original
ultima_fila <- nrow(original_df)
original_df <- original_df[-ultima_fila,]
original_df$agrupacion <- original_df$`Agrupación Política`
original_df$cantidad <- as.numeric(original_df$`N.º`)
original_df <- original_df[,c("agrupacion", "cantidad")]
# composición actual
tmp1 <- toString(actual_node) %>%
str_replace_all("\\[[^\\]]+\\]", "")
actual_df <- (read_html(tmp1) %>%
html_table(fill = TRUE, trim = TRUE))[[1]] %>%
janitor::clean_names() %>%
select(bancadas, conformacion) %>%
filter(
str_detect(bancadas,
pattern = "^(Bancadas|Total|Fuente|Restricc).*$",
negate = TRUE)
) %>%
rename(
agrupacion = bancadas,
cantidad = conformacion
) %>%
mutate( # el valor tiene caracteres UNICODE, forzar a ASCII
cantidad = stringi::stri_encode(cantidad, "", "ASCII") %>%
as.numeric()
)partidos <- original_df$agrupacion
ggplot(original_df2) +
geom_parliament(aes(seats = cantidad, fill = agrupacion)) +
scale_fill_manual(values = distinctColorPalette(13), labels = partidos) +
coord_fixed() +
labs(
title = "Congreso 2016-2021", subtitle = "Al inicio",
caption = "Fuente: Wikipedia"
) +
theme_void() +
theme(
legend.position = "right",
plot.margin = unit(rep(1, 4), "cm"),
legend.text = element_text(size = 8)
)
partidos <- actual_df$agrupacion
ggplot(actual_df) +
geom_parliament(aes(seats = cantidad, fill = agrupacion)) +
scale_fill_manual(values = distinctColorPalette(13), labels = partidos) +
coord_fixed() +
labs(
title = "Congreso 2016-2021",
subtitle = "En la actualidad",
caption = "Fuente: Wikipedia"
) +
theme_void() +
theme(
legend.position = "left",
plot.margin = unit(rep(1, 4), "cm"),
legend.text = element_text(size = 8)
)
ggplot(df_alluvial, aes(x = periodo, y = value, stratum = agrupacion,
alluvium = agrupacion, fill = agrupacion, label = label)) +
geom_flow(stat = "alluvium", lode.guidance = "rightleft",
color = "darkgray") +
geom_stratum() +
geom_text(stat = "stratum") +
scale_fill_manual(values = distinctColorPalette(13), labels = df_alluvial$agrupacion) +
labs(
title = "El Congreso 2016-2021",
subtitle = "Cambios en la composición de fuerzas",
caption = "Fuente: Wikipedia"
) +
theme_void() +
theme(
axis.title = element_blank(),
axis.text = element_blank(),
legend.position = "none"
)
pdftotext)crear_txt_df <- function(fname) {
txt <- readLines(fname, encoding = "utf-8") %>%
str_replace("Art\\.", "articulo") %>%
str_replace("art\\.", "artículo")
docs <- Corpus(VectorSource(txt)) %>%
tm_map(content_transformer(tolower)) %>%
tm_map(removeNumbers) %>%
tm_map(removeWords, stopwords("es")) %>%
tm_map(removeWords, c("artículo", "art", "articulo", "ser")) %>%
tm_map(removePunctuation) %>%
tm_map(stripWhitespace) %>%
tm_map(stemDocument)
tdm <- TermDocumentMatrix(docs)
m <- as.matrix(tdm)
v <- sort(rowSums(m),decreasing=TRUE)
tibble(word = names(v),freq=v)
}load(here::here("data/constitucion_peru_1812_1993.Rdata"))
c_1812 <- constitucion_peru %>%
filter(yr == 1812) %>%
top_n(n = 100, wt = freq)
ggplot(c_1812, aes(label = word, size = freq,
color = freq, angle = angle)) +
geom_text_wordcloud_area(rm_outside = TRUE, shape = "square") +
scale_size_area(max_size = 32) +
scale_fill_manual(values = randomColor(100, hue = "red")) +
labs(
title = "Nubes de palabras de la Constitución del Perú",
subtitle = "Año: 1812. Fuente: Congreso de la República del Perú.",
caption = "Tomando los 100 términos mas frecuentes en cada documento\n@jmcastagnetto (Jesus M. Castagnetto)"
) +
theme_minimal()
load(here::here("data/constitucion_peru_1812_1993.Rdata"))
c_1993 <- constitucion_peru %>%
filter(yr == 1993) %>%
top_n(n = 100, wt = freq)
ggplot(c_1993, aes(label = word, size = freq,
color = freq, angle = angle)) +
geom_text_wordcloud_area(rm_outside = TRUE, shape = "circle") +
scale_size_area(max_size = 32) +
scale_fill_manual(values = randomColor(100, hue = "blue")) +
labs(
title = "Nubes de palabras de la Constitución del Perú",
subtitle = "Año: 1993. Fuente: Congreso de la República del Perú.",
caption = "Tomando los 100 términos mas frecuentes en cada dinstall.packages("randomcoloR")ocumento\n@jmcastagnetto (Jesus M. Castagnetto)"
) +
theme_minimal()

airlines.dat: Lista de aerolíneas mundialesairports.dat: Lista de aeropuertos, geolocalizadoscountries.dat: Lista de países (con códigos ISO)routes.dat: Lista de las rutas (al 2014)load(here::here("data/peru-flights.Rdata"))
pe_flights %>%
e_charts() %>%
e_globe(
environment = ea_asset("starfield"),
base_texture = ea_asset("world topo"),
height_texture = ea_asset("world topo"),
displacementScale = 0.05
) %>%
e_lines_3d(
source_lon, source_lat,
dest_lon, dest_lat,
source_name = source_name,
target_name = dest_name,
name = "flights",
effect = list(show = TRUE)
) %>%
e_legend(FALSE)